<?php

class _F_EXTENSION_SCRIPT_ extends _F_EXTENSION_ {
	
	public $prev_callback;
	public $scripts = array(); 
	public $default_script_attrs = array();
	
	private $cnt = 0;
		
	public function __construct() {
		f()->register_method('script',array($this,'script'));
		f()->register_method('js',array($this,'js'));
		$this->prev_callback = f()->register_method(
			'post_process_callback',array($this,'_f_callback_'));
	}
	
	// TODO: es meg itt is vilagos es egyseges szabalyok kellenek
	//
	// 1. ami '/' jellel kezdodik az relativ a {base_path}-hoz kepest
	//
	// 2. ami '@' jellel kezdodik az a kovetkezo modon lesz feldolgozva:
	//		- ha letezik base_path/$theme/scripts/{file} akkor az
	//		- ha letezik base_path/scripts/{file} akkor az
	// 		- figyelmeztetest kuld es erintetlenul kerul be
	//
	// 3. minden mas erintetlenul kerul be a cuccosba

	public function script($script = null) {
		if (func_num_args() > 0) {
			if ($script{0} == '@') {
				$file = '/scripts/'.substr($script,1);
				$script = '/themes/'.f()->theme.$file;
				if (!file_exists(f()->base_path.$script)) $script = $file;
				if (!file_exists(f()->base_path.$script)) 
					error_log("VerSimF Notice: Script '$script' does not exist.");
			}
			$this->scripts['@'.$script] = null;
		}
		return $this;
	}

	public function js($js, $param = null) {
		if(is_array($js)) {
			$this->scripts['$'.($this->cnt++)] = $js;
		} else if($js{0} == '$') {
			$array = array();
			$array[substr($js,1)] = $param;
			$this->scripts['$'.($this->cnt++)] = $array;
		} else {
			$this->scripts['<'.($this->cnt++)] = $js;
		}
		return $this;
	}

	public function _f_callback_() {
		if (isset($this->prev_callback)) call_user_func($this->prev_callback);
		$buffer = '';
		foreach ($this->scripts as $script => $param) {
			$attr = $this->default_script_attrs;
			if ($script{0} === '@') { // external script
				$attr['src'] = f()->url(substr($script,1));
				$script = '';
			} else if ($script{0} === '$') { // one value
				$script = "\r\nvar ";
				$sep = '';
				foreach ($param as $name => $value) {
					$script .= $sep.$name.' = '.json_encode($value);
					$sep = ",\r\n\t";
				}
				$script .= ";\r\n";
			} else { // normal script
				$script = "\r\n".substr($script,1)."\r\n";
			}
			if (isset($params)) $attr = array_merge($attr,$params);
			$attr =	f()->attr($attr);
			$buffer .= "<script$attr>$script</script>\r\n";
		}
		f()->content = preg_replace('/<\/(body\s*)/im',"$buffer</$1",f()->content);
	}

}

new _F_EXTENSION_SCRIPT_;